import Vue from 'vue'
import Vuex from 'vuex'
import getters from './getters'
import app from './modules/app'
import settings from './modules/settings'
import storeConfigData from './storeConfig'

Vue.use(Vuex)
/**
 * Setting 和 App 的共享数据
 */
let storeForSettingAndApp = {
  modules: {
    app,
    settings,
  },
  getters,
};


/**
 * 处理转换store数据
 * @param storeList store数据
 * @returns store
 */
function transformationStore(storeList) {
  let tempStore = {
    state: {},
    getters: {},
    mutations: {}, //this.$store.commit('addUserInfo', item)
    actions: {}
  };
  storeList.forEach(item => {
    // count: JSON.parse(localStorage.getItem("count")) || "";
    if (item.storageMode == "local") {
      localStorage.setItem(item.key, JSON.stringify(item.keyValueDefaultValue));
      tempStore.state[item.key] = JSON.parse(localStorage.getItem(item.key));
    } else if (item.storageMode == "session") {
      sessionStorage.setItem(
        item.key,
        JSON.stringify(item.keyValueDefaultValue)
      );
      tempStore.state[item.key] = JSON.parse(sessionStorage.getItem(item.key));
    }

    tempStore.getters["get_" + item.key] = state => {
      return state[item.key];
    };
    item.actionList.forEach(actionItem => {
      tempStore.mutations[actionItem.funName] = actionItem.action;
    });
    item.actionList.forEach(actionItem => {
      tempStore.actions[actionItem.funName] = context => {
        context.commit(actionItem.funName);
      };
    });
  });
  return tempStore;
}

let storeData = transformationStore(storeConfigData);

let getterData = Object.assign({}, storeData["getters"], getters);
let storeData_ = Object.assign({}, storeForSettingAndApp, storeData, {
  getters: getterData,
});
const store = new Vuex.Store(storeData_);

/**
 * 设置store数据持久化的方式
 */
store.subscribe((mutations, store) => {
  let storageMode="";
  Object.keys(store).forEach((item) => {
    storeConfigData.forEach((item_) => {
      if (item_.key == item) {
        storageMode = item_.storageMode;
      }
    });
    if (storageMode == "local") {
      localStorage.setItem(item, JSON.stringify(store[item]));
    } else if (storageMode == "session") {
      sessionStorage.setItem(item, JSON.stringify(store[item]));
    }
  });
});

export default store
